<template>
  <el-dialog
    v-el-drag-dialog
    title="预约时间"
    :visible.sync="visible"
    width="600px"
    @closed="reset"
  >
    <el-form ref="dataForm" :model="temp">
      <!-- <el-form-item label="预约时间：">
        <div class="appointment">
          <p class="timeContent" @click="showAppointment">
            <span v-if="!currentDayContent" class="placeholder">请选择预约时间</span>
            <span v-else>{{ currentDayContent }}</span>
            <img v-show="showClear" src="@/assets/clear.png" alt="" @click="clearAppointment">
          </p>
          <el-card v-if="popoverVisible" class="appointment-warp">
            <div class="head">
              <i v-show="appointmentList&&appointmentList.length>1" class="el-icon-arrow-left" @click="forward" />
              <div v-for="(item,index) in currentAppointment" :key="index" :class="currentDayInfo.day===item?'appointment':''" @click="selectAppointment(item, index)">
                <span v-if="index===0">今天</span>
                <span v-if="index===1">明天</span>
                <span v-if="index===2">后天</span>
                <span>{{ item }}</span>
              </div>
              <i v-show="appointmentList&&appointmentList.length>1" class="el-icon-arrow-right" @click="future" />
            </div>
            <div v-loading="$loadingPlugin.gettimeList" class="content">
              <div v-for="(item, idx) in timePartList.appointmentTimeList" :key="idx" class="content-item">
                <div class="time-item">
                  <p :class="item.isFull?'p-disabel-gray':''" @click="selectTimePart(item,idx)">
                    <span :class="item.select?'time-active':''">{{ item.showIndex===0?currentAppointmentIndex===0?'今日送达':currentAppointmentIndex===1?'明日送达':currentAppointmentIndex===2?'后日送达':'':item.startTime+'~'+item.endTime }}</span><span v-if="item.isFull" class="dis">已约满</span><span v-if="!item.isFull && item.leftCount" class="left">{{ '(余' + item.leftCount + ')' }}</span>
                  </p>
                </div>
              </div>
              <p v-if="timePartList.appointmentTimeList.length===0" class="noAppointmentList">暂无可选时间段</p>
            </div>
            <div class="foot">
              <el-button size="mini" @click="popoverVisible = false">取 消</el-button>
              <el-button size="mini" type="primary" @click="confirmed">确 定</el-button>
            </div>
          </el-card>
        </div>
      </el-form-item> -->
      <div class="appointment">
        <div class="appointment-row">
          <div style="width: 105px;">预约时间</div>
          <p class="timeContent" @click="showAppointment">
            <span v-if="!currentDayContent" class="placeholder">请选择预约时间</span>
            <span v-else>{{ currentDayContent }}</span>
          </p>
        </div>
        <el-card v-if="popoverVisible" class="appointment-warp">
          <h4>请选择预约时间</h4>
          <div class="left">
            <div class="head">
              <i v-show="appointmentList&&appointmentList.length>1" class="el-icon-arrow-left" @click="forward" />
              <div v-for="(item,index) in currentAppointment" :key="index" :class="currentDayInfo.day===item?'appointment-select':''" @click="selectAppointment(item, index)">
                <span v-if="index===0">今天</span>
                <span v-if="index===1">明天</span>
                <span v-if="index===2">后天</span>
                <span>{{ item }}</span>
              </div>
              <i v-show="appointmentList&&appointmentList.length>1" class="el-icon-arrow-right" @click="future" />
            </div>
            <div v-loading="$loadingPlugin.gettimeList" class="content">
              <div v-for="(item, idx) in timePartList.appointmentTimeList" :key="idx" class="content-item" @click="selectTimePart(item,idx)">
                <div class="time-item">
                  <p v-if="item.dateFlag&&item.dateFlag===1" class="time-count">
                    <span :class="item.select?'time-active':''">{{ item.endTime }}前送达</span>
                  </p>
                  <p v-else class="time-count" :class="item.isFull?'p-disabel-gray':''">
                    <span :class="item.select?'time-active':''">{{ item.startTime+'~'+item.endTime }}</span><span v-if="item.isFull" class="dis">已约满</span><span v-if="(!item.isFull) && item.leftCount" class="count-left">{{ '(余' + item.leftCount + ')' }}</span>
                  </p>
                  <p v-if="item.select&&!item.isFull" :class="item.isFull?'p-disabel-gray':item.select?'time-active':''"> ✔ </p>
                </div>
              </div>
              <p v-if="timePartList.appointmentTimeList.length===0" class="noAppointmentList">暂无可选时间段</p>
            </div>

          </div>
          <div class="foot">
            <el-button size="mini" @click="popoverVisible = false">取 消</el-button>
            <el-button size="mini" type="primary" @click="confirmed">确 定</el-button>
          </div>
        </el-card>
      </div>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">
        取消
      </el-button>
      <el-button :loading="$loadingPlugin.changeTime" type="primary" @click="success">
        确定
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { parseTime } from '@/utils'
  import { accountopeningQuery, orderAppointment, queryOrderDetailData, updateAppointment } from '@/api'
  import moment from 'dayjs'
  export default {
    name: 'press-order',
    props: {
      parentFetchData: {
        type: Function
      }
    },
    data() {
      return {
        moment,
        visible: false,
        billCode: '',
        billType: 1,
        temp: {},
        popoverVisible: false,
        popoverVisibleDay: false,
        showClear: false,
        currentDayContent: '',
        appointmentList: [],
        currentAppointment: [],
        currentAppointmentIndex: 0,
        currentDayInfo: {},
        timePartList: [],
        confirmedDayInfo: {},
        appointmentInfo: {},
        radio: 1,
        clientSelected: {},
        commodityData: {},
        appointmentData: {}
      }
    },
    methods: {
      open(temp, clientSelected) {
        console.log('temp', temp)
        return new Promise(resolve => {
          this.resolve = resolve
          if (temp) {
            this.temp = temp
            this.clientSelected = clientSelected
            if (temp.appointmentDt) {
              this.appointmentData = temp
              this.currentDayContent = temp.appointmentTime || ''
            }
            this.appointmentInfo = temp
            this.orderDetail()
            this.gettimeList()
          }
          this.visible = true
        })
      },
      async orderDetail() {
        const res = await queryOrderDetailData({ orderCode: this.temp.orderCode })
        this.commodityData = res.data.detailList
      },
      getTimeClear() {
        this.appointmentList = []
        // this.appointmentInfo = {}
        this.currentAppointment = []
        this.currentAppointmentIndex = 0
        this.currentDayInfo = {}
        this.confirmedDayInfo = {}
        this.timePartList = {}
        this.currentDayContent = ''
      },
      async showAppointment() {
        const { data } = await accountopeningQuery({ orgId: this.appointmentInfo.orgId })
        this.currentAppointment = []
        const date = moment(new Date())
        if (data.range === 0) {
          this.currentAppointment.push(parseTime(date.format(), '{y}-{m}-{d}'))
        } else if (data.range === 1) {
          this.currentAppointment.push(parseTime(date.format(), '{y}-{m}-{d}'), parseTime(date.add(1, 'days').format(), '{y}-{m}-{d}'))
        } else if (data.range === 2) {
          this.currentAppointment.push(parseTime(date.format(), '{y}-{m}-{d}'), parseTime(date.add(1, 'days').format(), '{y}-{m}-{d}'), parseTime(date.add(2, 'days').format(), '{y}-{m}-{d}'))
        }
        this.currentDayInfo.day = parseTime(new Date(), '{y}-{m}-{d}')
        await this.gettimeList()
        console.log(this.confirmedDayInfo, this.currentDayContent, this.currentDayInfo, '------------')
        // console.log('date',date)
        console.log('currentAppointment', this.currentAppointment)
        // this.getTimeClear()
        if (this.appointmentInfo && (this.appointmentInfo.sp1 >> 4 & 0x01) === 1) {
          this.appointmentHandle()
        }
        if (this.confirmedDayInfo && this.confirmedDayInfo.day) {
          this.currentDayInfo.day = this.confirmedDayInfo.day
          await this.gettimeList()
          const c_item = this.timePartList.appointmentTimeList.findIndex(item => item.startTime === this.confirmedDayInfo.time.startTime)
          if (c_item) {
            this.timePartList.appointmentTimeList[c_item].select = true
          } else {
            this.timePartList.appointmentTimeList[0].select = true
          }
          this.currentDayInfo.time = this.confirmedDayInfo.time
        }
        this.popoverVisible = !this.popoverVisible
        this.popoverVisibleDay = false
      },
      clearAppointment() {
        this.popoverVisible = !this.popoverVisible
        this.showClear = false
      },
      async appointmentHandle() {
        console.log(this.appointmentInfo, '-------------')
        // this.appointmentList = this.appointmentInfo.appointmentTimes ? splitArray(this.appointmentInfo.appointmentTimes, 3) : []
        if (this.appointmentList.length > 0) {
          this.currentAppointment = this.appointmentList[0]
        }
        this.currentAppointmentIndex = 0
        if (this.currentAppointment.length > 0) {
          this.currentDayInfo.day = this.currentAppointment[0]
          await this.gettimeList()
          console.log(this.timePartList.appointmentTimeList)
          if (this.timePartList.appointmentTimeList && this.timePartList.appointmentTimeList.length > 0) {
            for (let i = 0; i <= this.timePartList.appointmentTimeList.length; i++) {
              if (!(this.timePartList.appointmentTimeList[i] && this.timePartList.appointmentTimeList[i].isFull)) {
                this.timePartList.appointmentTimeList[i].select = true
                this.currentDayInfo.time = this.timePartList.appointmentTimeList[i]
                break
              }
            }
          } else {
            const tomorrow = this.currentAppointment[this.currentAppointmentIndex + 1]
            this.selectAppointment(tomorrow, this.currentAppointmentIndex + 1)
          }
          console.log(this.appointmentList)
        }
      },

      forward() {
        if (this.currentAppointmentIndex > 0) this.currentAppointmentIndex--
        this.currentAppointment = this.appointmentList[this.currentAppointmentIndex]
      },
      future() {
        if (this.currentAppointmentIndex < (this.appointmentList.length - 1)) this.currentAppointmentIndex++
        this.currentAppointment = this.appointmentList[this.currentAppointmentIndex]
      },
      // 选中天
      async selectAppointment(val, index) {
        this.currentAppointmentIndex = index
        this.currentDayInfo.day = val
        this.currentDayInfo.time = null
        this.timePartList.appointmentTimeList = []
        await this.gettimeList()
        if (this.timePartList.appointmentTimeList && this.timePartList.appointmentTimeList.length > 0) {
          for (let i = 0; i <= this.timePartList.appointmentTimeList.length; i++) {
            if (!(this.timePartList.appointmentTimeList[i] && this.timePartList.appointmentTimeList[i].isFull)) {
              if (this.timePartList.appointmentTimeList[i]) {
                this.timePartList.appointmentTimeList[i].select = true
                this.currentDayInfo.time = this.timePartList.appointmentTimeList[i]
              }
              break
            }
          }
        }
      },
      // 选中时间段
      selectTimePart(val, index) {
        console.log(val)
        if (val.isFull) {
          this.$message.warning('该时段已约满')
          return
        } else {
          const i = this.timePartList.appointmentTimeList.findIndex(item => item.select)
          if (i !== -1) {
            this.timePartList.appointmentTimeList[i].select = false
            this.timePartList.appointmentTimeList[index].select = true
            this.currentDayInfo.time = val
          } else {
            this.timePartList.appointmentTimeList[index].select = true
            this.currentDayInfo.time = val
          }
        }
      },
      confirmed() {
        console.log(this.currentDayInfo)
        if (this.currentDayInfo.day && this.currentDayInfo.time) {
          this.currentDayContent = this.currentDayInfo.day + '  ' + this.currentDayInfo.time.startTime + '~' + this.currentDayInfo.time.endTime
          if (this.currentDayInfo.time.dateFlag === 1) {
            this.currentDayContent = this.currentDayInfo.day + '  ' + this.currentDayInfo.time.endTime + ' 前送达'
          }
          this.popoverVisible = false
          this.confirmedDayInfo = JSON.parse(JSON.stringify(this.currentDayInfo))
          this.radio = 2
          this.confirmedDayInfo2 = {}
        } else {
          if (this.timePartList.appointmentTimeList.length === 0) {
            this.$message.warning('无可选时间段')
          } else {
            this.$message.warning('请选择时间段')
          }
        }
      },
      // 获取时间段
      async gettimeList() {
        const params = {
          customerInfo: this.clientSelected,
          date: this.currentDayInfo.day || parseTime(new Date(), '{y}-{m}-{d}'),
          orgId: this.temp.orgId,
          csmId: this.clientSelected.csmId
        }
        const res = await orderAppointment(params)
        if (res && res.data) {
          this.timePartList = res.data
          const that = this
          let appointmentTimeList = []
          if (res.data.appointmentTimeList && res.data.appointmentTimeList.length > 0) {
            appointmentTimeList = res.data.appointmentTimeList
          }
          that.timePartList.appointmentTimeList = appointmentTimeList
          if (appointmentTimeList) {
            appointmentTimeList.forEach((item, index) => {
              that.commodityData.forEach((ele, orderI) => {
                item.appointmentList.forEach((e, idx) => {
                  if (e.goodsId === ele.goodsId) {
                    that.timePartList.appointmentTimeList[index].appointmentList[idx]['existAppointment'] = true
                  }
                  if (ele.goodsName.indexOf('15') > -1 && e.goodsId === ele.goodsId) {
                    item.idx = idx
                  }
                })
              })
            })

            that.timePartList.appointmentTimeList = that.timePartList.appointmentTimeList.map(item => ({
              ...item,
              select: false,
              leftCount: item.idx > -1 ? item.appointmentList[item.idx].leftCount : 0,
              isFull: item.appointmentList.some(item => item.existAppointment && item.status === 0)
            }))
          }
        }
      },
      dateDiff(interval, dt1, dt2) {
        if (!dt1) {
          dt1 = new Date()
        }
        if (!dt2) {
          dt2 = new Date()
        }
        if (arguments.length < 2) {
          return 0
        }
        var objInterval = {
          'D': 1000 * 60 * 60 * 24,
          'H': 1000 * 60 * 60,
          'M': 1000 * 60,
          'S': 1000,
          'T': 1
        }
        interval = interval.toUpperCase()
        // return Math.round((dt2.getTime() - dt1.getTime()) / eval('objInterval.' + interval))
        return Math.round((dt2.getTime() - dt1.getTime()) / objInterval[interval])
      },
      success() {
        if (this.$loadingPlugin.changeTime) return
        this.$refs.dataForm.validate(valid => {
          if (!valid) return
          this.changeTime()
        })
      },
      async changeTime() {
        let appointmentDt = ''
        let dateTimeSpare1 = ''
        if (!(this.confirmedDayInfo && this.confirmedDayInfo.time && this.confirmedDayInfo.time.startTime)) {
          this.$message.warning('预约时间无变化，请重新选择时间段')
          return
        }
        if (!this.confirmedDayInfo.time || !this.currentDayContent) {
          this.$message.error('请选择预约时间')
          return
        } else {
          appointmentDt = new Date(this.confirmedDayInfo.day + ' ' + this.confirmedDayInfo.time.startTime)
          dateTimeSpare1 = new Date(this.confirmedDayInfo.day + ' ' + this.confirmedDayInfo.time.endTime)
        }

        console.log(appointmentDt, dateTimeSpare1)
        const params = {
          orderCode: this.temp.orderCode,
          orgId: this.temp.orgId,
          detailList: this.commodityData,
          appointmentDt: appointmentDt,
          dateTimeSpare1: dateTimeSpare1
        }
        const res = await updateAppointment(params)
        if (res) {
          this.$notify({
            title: '提示',
            message: '修改成功!',
            type: 'success',
            duration: 2000
          })
          this.resolve()
          this.visible = false
        }
      },

      reset() {
        this.temp = {}
        this.popoverVisible = false
        this.showClear = false
        this.currentDayContent = ''
        this.appointmentList = []
        this.currentAppointment = []
        this.currentAppointmentIndex = 0
        this.currentDayInfo = {}
        this.timePartList = []
        this.confirmedDayInfo = {}
        this.confirmedDayInfo2 = {}
        this.appointmentInfo = {}
        this.$nextTick(() => {
          this.$refs.dataForm.clearValidate()
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
.appointment {
  position: relative;
  cursor: pointer;
  .appointment-row {
    display: flex;
    width: 100%;
  }
  .timeContent {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    border-bottom: 1px solid #dcdfe6;
    .placeholder {
      color: #c0c4cc;
    }
    img {
      width: 24px;
      height: 24px;
    }
  }
  .appointment-warp {
    width: 380px;
    transform: scale(0.9);
    h4 {
      margin: 0 0 8px 0;
      font-weight: 500;
      text-align: center;
      border-bottom: 1px solid #DCDFE6;
    }
    .left {
      display: flex;
      padding-bottom: 8px;
      border-bottom: 1px solid #DCDFE6;
    }
    .head {
      width: 100px;
      background-color: #d7d7d7;
      border-left: 1px solid #d7d7d7;
      div {
        width: 100%;
        padding: 10px 0;
        text-align: center;
        cursor: pointer;
        background-color: #d7d7d7;
        span {
          display: block;
          line-height: 20px;
        }
        &:hover {
          background: #EBEEF5;
        }
      }
      .appointment-select {
        color: $themeColor;
        background-color: white;
      }
      i {
        font-size: 24px;
      }
    }
    .content {
      flex: 1;
      min-height: 100px;
      .content-item {
        width: 100%;
        line-height: 30px;
        .time-item {
          display: flex;
          padding-left: 10px;
          &:hover {
            background: #EBEEF5;
          }
          p {
            min-width: 30px;
            text-align: center;
            cursor: pointer;
            span {
              display: block;
            }
            .dis {
              color: red;
            }
          }
          .time-count {
            display: flex;
            align-items: center;
            justify-content: flex-start;
            width: 200px;
            span:nth-child(1) {
              margin-right: 20px;
            }
          }

          .p-disabel-gray {
            span:nth-child(1) {
              color: #c0c4cc;
            }
          }
          .time-active {
            color: $themeColor;
            // background-color: rgba(19, 177, 177, 0.2);
          }
        }
      }
      .noAppointmentList {
        min-height: 162px;
        line-height: 162px;
        color: #c0c4cc;
        text-align: center;
      }
    }
    .foot {
      margin-top: 8px;
      text-align: right;
    }
  }
}
</style>
